package org.hcyspartnoc.luoxin.service.searchtopic.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hcyspartnoc.luoxin.common.core.configuration.ContrapsychConfiguration;
import org.hcyspartnoc.luoxin.common.core.configuration.UtilsConfiguration;
import org.hcyspartnoc.luoxin.common.core.context.BaseContextHolder;
import org.hcyspartnoc.luoxin.common.exception.common.CommonUtilsException;
import org.hcyspartnoc.luoxin.common.exception.searchtopic.QuestionBankException;
import org.hcyspartnoc.luoxin.common.exception.searchtopic.TopicException;
import org.hcyspartnoc.luoxin.mapper.searchtopic.QuestionMapper;
import org.hcyspartnoc.luoxin.mapper.searchtopic.TopicMapper;
import org.hcyspartnoc.luoxin.pojo.dto.searchtopic.QuestionBankDto;
import org.hcyspartnoc.luoxin.pojo.dto.searchtopic.TopicPictureDto;
import org.hcyspartnoc.luoxin.pojo.dto.searchtopic.TopicRagDto;
import org.hcyspartnoc.luoxin.pojo.dto.searchtopic.TopicTextDto;
import org.hcyspartnoc.luoxin.pojo.po.searchtopic.QuestionBankPo;
import org.hcyspartnoc.luoxin.pojo.po.searchtopic.QuestionPo;
import org.hcyspartnoc.luoxin.pojo.po.searchtopic.TopicPo;
import org.hcyspartnoc.luoxin.pojo.vo.searchtopic.QuestionBankVO;
import org.hcyspartnoc.luoxin.pojo.vo.searchtopic.QuestionVo;
import org.hcyspartnoc.luoxin.pojo.vo.searchtopic.TopicVO;
import org.hcyspartnoc.luoxin.service.searchtopic.TopicService;
import org.hcyspartnoc.luoxin.utils.AliyunOssUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private ContrapsychConfiguration contrapsychConfiguration;

    @Autowired
    private UtilsConfiguration utilsConfiguration;

    @Autowired
    private AliyunOssUtils aliyunOssUtils;

    @Override
    public TopicVO createTopic(MultipartFile image) throws TopicException, CommonUtilsException{

        // 验证图像文件合法性
        if (image.isEmpty()) {
            throw new CommonUtilsException(CommonUtilsException.SRC_NOT_RIGHT);
        }
        String originalFilename = null;
        //获取原始的文件名
        if (Objects.isNull(originalFilename = image.getOriginalFilename()))
            throw new CommonUtilsException(CommonUtilsException.SRC_NOT_RIGHT);
        //在oss中存储名字就是UUID + 文件的后缀名
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (!utilsConfiguration.getFile().getAllowedImageTypes().contains(fileExtension.toUpperCase()))
            throw new CommonUtilsException(CommonUtilsException.SRC_NOT_RIGHT);
        String objectName = UUID.randomUUID() + "." + fileExtension;
        try {
            String resultURL = aliyunOssUtils.upload(image.getBytes(), objectName);
            if (Objects.isNull(resultURL)) {
                throw new CommonUtilsException(CommonUtilsException.SRC_UPLOAD_FAIL);
            }
            try {
                    // 创建HttpClient对象
            HttpClient client = HttpClient.newHttpClient();
            TopicPictureDto topicPictureDto = new TopicPictureDto();
            topicPictureDto.setImageUrl(resultURL);

            // 将 PictureTopicDto 转为JSON
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(topicPictureDto);

            // 创建HttpRequest对象
            HttpRequest request = HttpRequest.newBuilder()
//                    .uri(URI.create("http://127.0.0.1:9091/AI/GLM_4V_picture"))
                    .uri(URI.create(contrapsychConfiguration.getTopic().getImageUrl()))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            // 发送请求并接收响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 检查响应状态码
            if (response.statusCode() != 200) {
                throw new TopicException(TopicException.REQUEST_FAILED + response.body());
            }
            TopicPo topicPo = new TopicPo();
            topicPo.setUserId(BaseContextHolder.getContext().getBaseCurrentUser().getId());
            topicPo.setCreatedTime(LocalDateTime.now());
            topicPo.setUpdatedTime(LocalDateTime.now());
            topicPo.setImageUrl(resultURL);
            topicMapper.createTopic(topicPo);
            // 将响应结果转为 PictureTopicVO 对象
            TopicVO topicVO = new TopicVO();
            BeanUtils.copyProperties(topicPo, topicVO);
            JsonNode rootNode = objectMapper.readTree(response.body());
            topicVO.setAnswer(String.valueOf(rootNode.path("result").path("choices").get(0).path("message").path("content")));
//            topicVO.setAnswer(response.body());
            return topicVO;
            } catch (Exception e) {
                throw new TopicException(TopicException.SERVER_ERROR + e.getMessage());
            }
        } catch (IOException e) {
            throw new CommonUtilsException(CommonUtilsException.SRC_UPLOAD_FAIL);
        }
    }

    @Override
    public void deleteTopicByid(Integer pictureTopicId) throws TopicException {
        TopicPo topicPo = topicMapper.getTopicByid(pictureTopicId);
        if (topicPo == null){
            throw new TopicException(TopicException.TOPIC_NOT_FOUND);
        }
        topicMapper.deleteByid(pictureTopicId);
    }

    @Override
    public List<TopicVO> getPictureTopic() throws TopicException {
        Integer userId = BaseContextHolder.getContext().getBaseCurrentUser().getId();
        List<TopicPo> topicPoList = topicMapper.getTopicByUserId(userId);

        List<TopicVO> topicVOList = topicPoList.stream().map(topicPo -> {
            TopicVO topicVO = new TopicVO();
            BeanUtils.copyProperties(topicPo, topicVO);
            return topicVO;
        }).collect(Collectors.toList());
        if(topicVOList.isEmpty()){
            throw new TopicException(TopicException.TOPIC_EMPTY);
        }
        return topicVOList;
    }

    @Override
    public TopicVO createTextTopic(TopicTextDto topicTextDto) throws TopicException{
        try {
            // 创建HttpClient对象
            HttpClient client = HttpClient.newHttpClient();

            // 将 PictureTopicDto 转为JSON
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> requestBodyMap = new HashMap<>();
            requestBodyMap.put("query", topicTextDto.getQuery()); // 封装为 JSON 对象
            String requestBody = objectMapper.writeValueAsString(requestBodyMap);

            // 创建HttpRequest对象
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(contrapsychConfiguration.getTopic().getTextUrl()))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            // 发送请求并接收响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 检查响应状态码
            if (response.statusCode() != 200) {
                throw new TopicException(TopicException.REQUEST_FAILED + response.body());
            }
            TopicPo topicPo = topicMapper.getTopicByid(topicTextDto.getId());
            if(topicPo == null){
                TopicPo topicTextPo = new TopicPo();
                JsonNode rootNode = objectMapper.readTree(response.body());
                Integer userId = BaseContextHolder.getContext().getBaseCurrentUser().getId();
                topicTextPo.setUserId(userId);
                topicTextPo.setQuery(topicTextDto.getQuery());
                topicTextPo.setUpdatedTime(LocalDateTime.now());
                topicTextPo.setCreatedTime(LocalDateTime.now());
                topicTextPo.setAnswer(String.valueOf(rootNode.path("result").path("choices").get(0).path("message").path("content")));
                topicMapper.createTopic(topicTextPo);
                // 将响应结果转为 PictureTopicVO 对象
                TopicVO topicVO = new TopicVO();
                BeanUtils.copyProperties(topicTextPo, topicVO);
                return topicVO;
            }
            JsonNode rootNode = objectMapper.readTree(response.body());
            topicPo.setQuery(topicTextDto.getQuery());
            topicPo.setUpdatedTime(LocalDateTime.now());
            topicPo.setAnswer(String.valueOf(rootNode.path("result").path("choices").get(0).path("message").path("content")));
            topicMapper.updateTopic(topicPo);
            // 将响应结果转为 PictureTopicVO 对象
            TopicVO topicVO = new TopicVO();
            BeanUtils.copyProperties(topicPo, topicVO);
            return topicVO;
        } catch (Exception e) {
            throw new TopicException(TopicException.SERVER_ERROR + e.getMessage());
        }
    }

    @Override
    public QuestionVo searchTopicByRag(TopicRagDto topicRagDto) throws TopicException {
        try {
            // 创建HttpClient对象
            HttpClient client = HttpClient.newHttpClient();

            // 将 TopicRagDto 转为JSON
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> requestBodyMap = new HashMap<>();
            StringBuilder options = new StringBuilder();
            if(!topicRagDto.getOptions().isEmpty()){
                for(TopicRagDto.QuestionOptions option : topicRagDto.getOptions()){
                    options.append(option.getOption());
                }
            }

            requestBodyMap.put("topic", topicRagDto.getQueTopic()); // 封装为 JSON 对象
            requestBodyMap.put("answer", topicRagDto.getQueAnswer());
            requestBodyMap.put("options",options.toString());
            String requestBody = objectMapper.writeValueAsString(requestBodyMap);

            // 创建HttpRequest对象
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(contrapsychConfiguration.getTopic().getTextUrl()))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            // 发送请求并接收响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 检查响应状态码
            if (response.statusCode() != 200) {
                throw new TopicException(TopicException.REQUEST_FAILED + response.body());
            }
            JsonNode rootNode = objectMapper.readTree(response.body());
            QuestionPo questionPo = new QuestionPo();
            questionPo.setAiAnalysis(String.valueOf(rootNode.path("result").path("choices").get(0).path("message").path("content")));
            questionMapper.updateQuestion(questionPo);
            QuestionVo questionVo = new QuestionVo();
            BeanUtils.copyProperties(topicRagDto,questionVo);
            questionVo.setAiAnalysis(String.valueOf(rootNode.path("result").path("choices").get(0).path("message").path("content")));
            questionVo.addOptionByRag(topicRagDto);
            return questionVo;
        } catch (Exception e) {
            throw new TopicException(TopicException.SERVER_ERROR + e.getMessage());
        }
    }
}

